<template>
  <div class="recruiter-jobs">
    <div class="page-header">
      <h2 class="page-title">职位管理</h2>
      <el-button type="primary" @click="handleCreateJob">
        <el-icon><Plus /></el-icon>发布新职位
      </el-button>
    </div>

    

    <!-- 职位列表 -->
    <el-card class="job-list">
      <el-table :data="jobList" style="width: 100%" v-loading="loading">
        <el-table-column label="职位信息" min-width="300">
          <template #default="{ row }">
            <div class="job-info">
              <div class="title">{{ row.title }}</div>
              <div class="meta">
                <el-tag size="small">{{ row.salary }}</el-tag>
                <el-tag size="small" type="info">{{ row.city }}</el-tag>
                <el-tag size="small" type="warning">{{ row.experience }}</el-tag>
                <el-tag size="small" type="success">{{ row.education }}</el-tag>
              </div>
              <div class="job-tags" v-if="row.tags">
                <el-tag 
                  v-for="tag in row.tags.split(',')" 
                  :key="tag"
                  size="small"
                  type="primary"
                  class="tag-item"
                  v-show="tag.trim()"
                >
                  {{ tag.trim() }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="投递情况" width="200">
          <template #default="{ row }">
            <div class="application-stats">
              <div class="stat-item">
                <span class="label">收到简历：</span>
                <span class="value">{{ applicationStats[row.id]?.total || 0 }}</span>
              </div>
              <div class="stat-item">
                <span class="label">待处理：</span>
                <span class="value highlight">{{ applicationStats[row.id]?.pending || 0 }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="薪资" prop="salary" width="120" />
        <el-table-column label="浏览" prop="viewCount" width="80" align="center" />
        <el-table-column label="申请" prop="applyCount" width="80" align="center" />
        <el-table-column label="发布时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewApplications(row)">查看简历</el-button>
            <el-button link type="primary" @click="editJob(row)">编辑</el-button>
            <!-- 下线按钮 -->
<el-button 
  v-if="row.status === 1"
  link 
  type="danger" 
  @click="offlineJob(row)"
>
  下线
</el-button>

<!-- 上线/重新提交按钮 -->
<el-button 
  v-if="row.status === 3 || row.status === 2"
  link 
  type="success" 
  @click="onlineJob(row)"
>
  重新提交
</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 职位表单对话框 -->
    <el-dialog
      v-model="jobDialogVisible"
      :title="jobForm.id ? '编辑职位' : '发布新职位'"
      width="700px"
    >
      <el-form :model="jobForm" label-width="100px" :rules="jobRules">
        <el-form-item label="职位名称" prop="title">
          <el-input v-model="jobForm.title" placeholder="请输入职位名称" />
        </el-form-item>
        <el-form-item label="职位分类" prop="categoryId">
          <el-select v-model="jobForm.categoryId" placeholder="请选择">
            <el-option label="全职" :value="1" />
            <el-option label="兼职" :value="2" />
            <el-option label="实习" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作城市" prop="city">
          <el-select v-model="jobForm.city" placeholder="请选择">
            <el-option label="北京" value="北京" />
            <el-option label="上海" value="上海" />
            <el-option label="广州" value="广州" />
            <el-option label="深圳" value="深圳" />
            <el-option label="杭州" value="杭州" />
          </el-select>
        </el-form-item>
        <el-form-item label="薪资范围" prop="salary">
          <el-select v-model="jobForm.salary" placeholder="请选择">
            <el-option label="面议" value="面议" />
            <el-option label="8k-15k" value="8k-15k" />
            <el-option label="15k-25k" value="15k-25k" />
            <el-option label="25k-35k" value="25k-35k" />
            <el-option label="35k-50k" value="35k-50k" />
            <el-option label="50k以上" value="50k+" />
          </el-select>
        </el-form-item>
        <el-form-item label="经验要求" prop="experience">
          <el-select v-model="jobForm.experience" placeholder="请选择">
            <el-option label="应届生" value="应届生" />
            <el-option label="1-3年" value="1-3年" />
            <el-option label="3-5年" value="3-5年" />
            <el-option label="5-10年" value="5-10年" />
            <el-option label="10年以上" value="10年+" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历要求" prop="education">
          <el-select v-model="jobForm.education" placeholder="请选择">
            <el-option label="大专" value="大专" />
            <el-option label="本科" value="本科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="博士" value="博士" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位描述" prop="description">
          <el-input
            v-model="jobForm.description"
            type="textarea"
            :rows="6"
            placeholder="请输入职位描述"
          />
        </el-form-item>
        <el-form-item label="职位要求" prop="requirement">
          <el-input
            v-model="jobForm.requirement"
            type="textarea"
            :rows="6"
            placeholder="请输入职位要求"
          />
        </el-form-item>
        <el-form-item label="职位标签" prop="tags">
          <el-tag
            v-for="tag in jobForm.tags"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleTagClose(tag)"
            class="tag-item"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputTagVisible"
            ref="tagInputRef"
            v-model="tagInputValue"
            class="tag-input"
            size="small"
            @keyup.enter="handleTagConfirm"
            @blur="handleTagConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showTagInput">
            + 添加标签
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="jobDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitJob" :loading="submitLoading">
            {{ jobForm.id ? '保存' : '发布' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRecruiterJobs, createJob, updateJob, updateJobStatus, getJobApplicationStats } from '@/api/job'
import { useRouter } from 'vue-router'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  title: '',
  status: ''
})

// 加载状态
const loading = ref(false)
const submitLoading = ref(false)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 职位列表数据
const jobList = ref([])

// 投递统计数据缓存 {jobId: {total: x, pending: y}}
const applicationStats = ref({})

// 获取职位列表
const fetchJobList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      title: searchForm.title || undefined,
      status: searchForm.status || undefined
    }
    
    const res = await getRecruiterJobs(params)
    if (res.code === 200) {
      jobList.value = res.data.records
      total.value = res.data.total
      
      // 增强调试：详细记录所有职位数据
      console.log('===== 职位数据全字段分析 =====')
      console.log(`总记录数: ${res.data.records.length}`)
      
      if (res.data.records && res.data.records.length > 0) {
        // 输出第一条职位记录的所有字段
        const firstJob = res.data.records[0]
        console.log('职位数据示例 (ID: ' + firstJob.id + ')')
        
        // 列出所有字段及其值
        console.log('所有字段列表:')
        Object.keys(firstJob).forEach(key => {
          console.log(`- ${key}: ${typeof firstJob[key] === 'object' ? JSON.stringify(firstJob[key]) : firstJob[key]}`)
        })
        
        // 特别关注requirement相关字段
        console.log('职位要求相关字段检查:')
        console.log('- requirement:', firstJob.requirement)
        console.log('- requirements:', firstJob.requirements)
        console.log('- jobRequirement:', firstJob.jobRequirement)
        console.log('- jobRequirements:', firstJob.jobRequirements)
        
        // 搜索所有可能包含"require"或"要求"的字段
        console.log('潜在的职位要求字段:')
        Object.keys(firstJob).filter(key => 
          key.toLowerCase().includes('require') || 
          key.includes('要求')
        ).forEach(key => {
          console.log(`- ${key}: ${firstJob[key]}`)
        })
      }
      console.log('================================')
      
      // 获取每个职位的投递统计
      await fetchApplicationStats()
    } else {
      ElMessage.error(res.message || '获取职位列表失败')
    }
  } catch (error) {
    console.error('获取职位列表失败', error)
    ElMessage.error('获取职位列表失败')
  } finally {
    loading.value = false
  }
}

// 获取职位投递统计
const fetchApplicationStats = async () => {
  try {
    const promises = jobList.value.map(job => {
      return getJobApplicationStats(job.id)
        .then(res => {
          if (res.code === 200) {
            // 将统计数据存储到缓存对象中
            applicationStats.value[job.id] = res.data
          }
          return res
        })
        .catch(err => {
          console.error(`获取职位ID ${job.id} 的投递统计失败:`, err)
          return null
        })
    })
    
    // 等待所有请求完成
    await Promise.allSettled(promises)
  } catch (error) {
    console.error('获取投递统计数据失败:', error)
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    0: "warning",  // 待审核
    1: "success",  // 已通过
    2: "danger",   // 已拒绝
    3: "info"      // 已下线
  }
  return map[status] || "info"
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    0: "待审核",
    1: "已通过",
    2: '已拒绝',
    3: '已下线'
  }
  return map[status] || '未知状态'
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchJobList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  fetchJobList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchJobList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchJobList()
}

// 职位表单相关
const jobDialogVisible = ref(false)
const jobForm = reactive({
  id: '',
  title: '',
  city: '',
  salary: '',
  experience: '',
  education: '',
  description: '',
  requirement: '',
  categoryId: null, // 职位分类：1-全职 2-兼职 3-实习
  tags: []
})

// 标签输入相关
const tagInputRef = ref(null)
const inputTagVisible = ref(false)
const tagInputValue = ref('')

// 显示标签输入框
const showTagInput = () => {
  inputTagVisible.value = true
  nextTick(() => {
    tagInputRef.value?.input?.focus()
  })
}

// 处理标签确认添加
const handleTagConfirm = () => {
  if (tagInputValue.value) {
    if (!jobForm.tags.includes(tagInputValue.value)) {
      jobForm.tags.push(tagInputValue.value)
    }
  }
  inputTagVisible.value = false
  tagInputValue.value = ''
}

// 处理标签删除
const handleTagClose = (tag) => {
  jobForm.tags = jobForm.tags.filter(t => t !== tag)
}

// 表单校验规则
const jobRules = {
  title: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
  city: [{ required: true, message: '请选择工作城市', trigger: 'change' }],
  salary: [{ required: true, message: '请选择薪资范围', trigger: 'change' }],
  experience: [{ required: true, message: '请选择经验要求', trigger: 'change' }],
  education: [{ required: true, message: '请选择学历要求', trigger: 'change' }],
  description: [{ required: true, message: '请输入职位描述', trigger: 'blur' }],
  requirement: [{ required: true, message: '请输入职位要求', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择职位分类', trigger: 'change' }],
  tags: [{ required: true, message: '请添加职位标签', trigger: 'change' }]
}

// 创建新职位
const handleCreateJob = () => {
  // 清空表单
  delete jobForm.id
  jobForm.title = ''
  jobForm.city = ''
  jobForm.salary = ''
  jobForm.experience = ''
  jobForm.education = ''
  jobForm.description = ''
  jobForm.requirement = ''
  jobForm.categoryId = null
  jobForm.tags = []
  
  jobDialogVisible.value = true
}

// 编辑职位
const editJob = (row) => {
  // 调试代码，检查传入的职位数据
  console.log('编辑职位原始数据：', row)
  
  Object.keys(jobForm).forEach(key => {
    if (row[key] !== undefined) {
      // 处理tags字段，将字符串转换为数组
      if (key === 'tags') {
        if (typeof row[key] === 'string') {
          // 分割字符串并过滤空值
          jobForm[key] = row[key] ? row[key].split(',').filter(tag => tag.trim()) : []
        } else if (Array.isArray(row[key])) {
          // 如果已经是数组，则直接使用
          jobForm[key] = row[key]
        } else {
          // 其他情况设为空数组
          jobForm[key] = []
        }
      } else {
        jobForm[key] = row[key]
      }
    }
  })
  
  console.log('处理后的职位要求字段：', jobForm.requirement)
  
  jobDialogVisible.value = true
}

// 提交职位
const submitJob = async () => {
  submitLoading.value = true
  try {
    // 处理表单数据
    const formData = { ...jobForm }
    
    // 将标签数组转换为逗号分隔的字符串
    if (Array.isArray(formData.tags)) {
      // 过滤空值并去除每个标签的首尾空格
      formData.tags = formData.tags
        .filter(tag => tag && tag.trim())
        .map(tag => tag.trim())
        .join(',')
    } else if (typeof formData.tags === 'string') {
      // 如果已经是字符串，确保格式正确
      formData.tags = formData.tags
        .split(',')
        .filter(tag => tag && tag.trim())
        .map(tag => tag.trim())
        .join(',')
    } else {
      // 其他情况设为空字符串
      formData.tags = ''
    }
    
    // 详细记录提交的数据
    console.log('===== 提交职位数据详情 =====')
    console.log('提交方式:', formData.id ? '更新' : '新建')
    console.log('职位表单数据:', formData)
    console.log('职位要求字段:', formData.requirement)
    
    let res;
    if (formData.id) {
      // 更新职位
      const jobId = formData.id
      // 删除id字段避免后端反序列化错误
      delete formData.id
      console.log('发送更新请求，职位ID:', jobId)
      res = await updateJob(jobId, formData)
    } else {
  // 创建新职位
  // 无条件删除id字段，确保不会发送到后端
  delete formData.id
  // 显式设置状态为待审核(0)
  formData.status = 0
  console.log('发送创建请求，初始状态设为待审核(0)')
  res = await createJob(formData)
}
    
    // 记录API响应
    console.log('API响应:', res)
    
    if (res.code === 200) {
      // 如果API返回了保存后的数据，检查是否包含requirement字段
      if (res.data) {
        console.log('保存后的职位数据:', res.data)
        console.log('保存后的requirement字段:', res.data.requirement)
        
        // 如果返回的数据没有requirement字段，记录所有字段用于分析
        if (res.data.requirement === undefined || res.data.requirement === null) {
          console.log('保存后数据的所有字段:')
          Object.keys(res.data).forEach(key => {
            console.log(`- ${key}: ${typeof res.data[key] === 'object' ? JSON.stringify(res.data[key]) : res.data[key]}`)
          })
        }
      }
      console.log('================================')
      
      ElMessage.success(jobForm.id ? '职位已更新' : '职位已发布')
      jobDialogVisible.value = false
      fetchJobList()
    } else {
      ElMessage.error(res.message || '提交失败')
    }
  } catch (error) {
    console.error('提交职位失败', error)
    ElMessage.error('提交职位失败')
  } finally {
    submitLoading.value = false
  }
}

// 下线职位
const offlineJob = async (row) => {
  try {
    await ElMessageBox.confirm('确定要下线该职位吗？', '提示', {
      type: 'warning'
    })
    
    const res = await updateJobStatus(row.id, 3) // 状态3表示已下线
    if (res.code === 200) {
      ElMessage.success('职位已下线')
      fetchJobList()
    } else {
      ElMessage.error(res.message || '下线失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('下线职位失败', error)
      ElMessage.error('下线职位失败')
    }
  }
}

// 上线职位
const onlineJob = async (row) => {
  try {
    await ElMessageBox.confirm('确定要重新上线该职位吗？', '提示', {
      type: 'warning'
    })
    
    const res = await updateJobStatus(row.id, 0) // 状态0表示待审核
if (res.code === 200) {
  ElMessage.success('职位已提交审核')
  fetchJobList()
} else {
      ElMessage.error(res.message || '上线失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('上线职位失败', error)
      ElMessage.error('上线职位失败')
    }
  }
}

// 重新提交职位
const resubmitJob = (row) => {
  editJob(row)
}

// 查看简历投递情况
const viewApplications = (row) => {
  router.push({
    path: `/recruiter/applications`,
    query: { jobId: row.id }
  })
}

// 格式化时间显示
const formatTime = (timeStr) => {
  if (!timeStr) return '未知';
  
  try {
    const date = new Date(timeStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (e) {
    console.error('日期格式化错误:', e);
    return timeStr;
  }
}

// 初始化
fetchJobList()
</script>

<style lang="scss" scoped>
.recruiter-jobs {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .job-list {
    flex: 1;
    display: flex;
    flex-direction: column;

    .el-card__body {
      height: 100%;
      display: flex;
      flex-direction: column;
    }

    .el-table {
      flex: 1;
    }

    .job-info {
      .title {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 8px;
        color: #303133;
      }

      .meta {
        display: flex;
        gap: 8px;
        margin-bottom: 8px;
      }
      
      .job-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
        
        .tag-item {
          margin-right: 4px;
        }
      }
    }

    .application-stats {
      .stat-item {
        margin-bottom: 4px;
        font-size: 14px;

        .label {
          color: #909399;
        }

        .value {
          font-weight: 600;
          margin-left: 4px;

          &.highlight {
            color: #f56c6c;
          }
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .tag-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }

  .button-new-tag {
    margin-right: 10px;
    height: 32px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .tag-input {
    width: 90px;
    margin-right: 10px;
    vertical-align: bottom;
  }
}
</style> 